package com.zsummer.baikal.common.config.security;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zsummer
 * @since 2021/7/28
 */
@Component
public class TokenManager {

    /**
     * token有效时常
     */
    @Value("${jwt.tokenExperiment}")
    private int tokenExperiment;

    /**
     * 密钥
     */
    @Value("${jwt.signingKey}")
    private String signingKey;

    public static final String BEARER = "Bearer ";

    /**
     * 创建token
     * @param username
     * @return
     */
    public String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .setExpiration(DateUtil.offset(new Date(), DateField.SECOND, tokenExperiment))
                .signWith(SignatureAlgorithm.HS256, signingKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 从token中获取用户名
     * @param token
     * @return
     */
    public String getUserName(String token) {
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody().getSubject();
    }

}
